import { Component } from '@angular/core';
import { IonicPage, NavController, NavParams, AlertController } from 'ionic-angular';
import { QRScanner, QRScannerStatus } from '@ionic-native/qr-scanner';

/**
 * Generated class for the ScanPage page.
 *
 * See https://ionicframework.com/docs/components/#navigation for more info on
 * Ionic pages and navigation.
 */

@IonicPage()
@Component({
  selector: 'page-scan',
  templateUrl: 'scan.html',
})
export class ScanPage {

  constructor(public navCtrl: NavController, public navParams: NavParams, public qrScanner: QRScanner, public alertCtrl: AlertController) {
  }

  // 页面加完执行的钩子函数
  ionViewDidLoad() {
    console.log('ionViewDidLoad ScanPage');
  }

  // 页面执行完居后。 

  ionViewDidEnder() {
    this.scanQRCode();
  }

  scanQRCode() {
    // Optionally request the permission early
    console.log('ol')
    this.qrScanner.prepare()
    .then((status: QRScannerStatus) => {
      if (status.authorized) {// 判断是否有权限
        // camera permission was granted
        window.document.querySelector('body').classList.add('transparent-body');

        // start scanning
        let scanSub = this.qrScanner.scan().subscribe((text: string) => {
          console.log('Scanned something', text);
          let alert = this.alertCtrl.create({
            title: '二维码内容',
            subTitle: text,
            buttons: ['OK']
          });
          alert.present();
          this.qrScanner.hide(); // hide camera preview
          scanSub.unsubscribe(); // stop scanning
        });

      } else if (status.denied) {
        // camera permission was permanently denied
        // you must use QRScanner.openSettings() method to guide the user to the settings page
        // then they can grant the permission from there
      } else {
        // permission was denied, but not permanently. You can ask for permission again at a later time.
      }
    })
    .catch((e: any) => console.log('Error is', e));

  }
}
